import React, { useLayoutEffect } from 'react';
import { useActions, useProps, useDevice, } from '@ray-js/panel-sdk';
import { View, Image, router, publishDps, navigateTo, hideMenuButton } from '@ray-js/ray';
import {
  Switch,
  NavBar,
  CellGroup,
  Cell,
  ActionSheet,
  DialogInstance,
  Dialog,
} from '@ray-js/smart-ui';
import { useDispatch, useSelector } from 'react-redux';
import styles from './index.module.less';
import Strings from '@/i18n';
import { removeAllSchedule } from '@/pages/schedule/utils';
import res from '@/res';
import { updateTimerList } from '@/redux/modules/scheduleStateSlice';

import { ReduxState } from '@/redux';

const single = 'single';
const same = 'same';
const conflict = 'conflict';

const forward = 'forward';
const back = 'back';

const low_speed = 'low_speed';
const medium_speed = 'medium_speed';
const high_speed = 'high_speed';

export default function Home() {
  const {
    curtain_mode: curtainMode,
    motor_pairing: motorPairing,
    motor_speed_regulation: speed,
    control_back: controlBack,
    motor_reverse: motorReverse,
  } = useProps();

  // const support = useSupport();

  const { timerList } = useSelector((state: ReduxState) => ({
    timerList: state.scheduleState.timerList,
  }));

  const [list, setAction] = React.useState([]);

  const [show, setShow] = React.useState(false);
  const [title, setTitle] = React.useState('');

  const setList = action => {
    setShow(true);
    setAction(action);
  };
  // single, same, conflict
  const modeActions = [single, same, conflict].map(item => ({
    name: Strings.getLang(item),
    id: item,
    checked: item === curtainMode,
    className: styles.actionSheetItem,
  }));

  const controlActions = [forward, back].map(item => ({
    name: Strings.getLang(item),
    id: item,
    checked: item === controlBack,
    className: styles.actionSheetItem,
  }));

  const speedActions = [low_speed, medium_speed, high_speed].map(item => ({
    name: Strings.getLang(item),
    id: item,
    checked: item === speed,
    className: styles.actionSheetItem,
  }));

  const deviceName = useDevice(d => d.devInfo.name);
  const deviceId = useDevice(d => d.devInfo.devId);
  const groupId = useDevice(d => d.devInfo.groupId);
  const actions = useActions();
  const dispatch = useDispatch();

  useLayoutEffect(() => {
    hideMenuButton();
  }, []);

  const onClickLeft = () => {
    router.back();
  };

  const onCancel = () => setShow(false);
  const onClose = () => setShow(false);
  const onSelect = evt => {
    const { id } = evt.detail;

    if (title === 'curtain_mode') {
      if (curtainMode !== id && timerList.length) {
        DialogInstance.confirm({
          selector: '#smart-dialog2',
          title: Strings.getLang('changeCurtainMode'),
          message: Strings.getLang('changeCurtainModeTip'),
        })
          .then((...params) => {
            console.log(params, 'params');
            removeAllSchedule().then(() => {
              publishDps({
                curtain_mode: id,
              });
              dispatch(updateTimerList([]));
              DialogInstance.close();
            });
          })
          .catch(() => {
            DialogInstance.close();
          });
      } else {
        publishDps({
          curtain_mode: id,
        });
      }
    } else {
      publishDps({
        [title]: id,
      });
    }
  };

  return (
    <View className={styles.view}>
      <NavBar
        leftArrow
        onClickLeft={onClickLeft}
        title={deviceName}
        className={styles.navBar}
        slot={{
          right: (
            <View className={styles.tabTopIconWrap}>
              {['setting'].map(item => (
                <Image
                  onClick={() => {
                    const jumpUrl = `functional://settings/detail?deviceId=${
                      deviceId || ''
                    }&groupId=${groupId || ''}`;

                    navigateTo({
                      url: jumpUrl,
                    });

                    // tabItem?.callback();
                  }}
                  src={res.setting}
                  key={item}
                />
              ))}
            </View>
          ),
        }}
      />
      <View>
        <CellGroup>
          <Cell
            title={Strings.getLang('curtain_mode')}
            value={Strings.getLang(curtainMode)}
            isLink
            onClick={() => {
              setTitle('curtain_mode');
              setList(modeActions);
            }}
          />
          {motorPairing !== undefined ? (
            <Cell title={Strings.getLang('motor_pairing')}>
              <Switch
                checked={motorPairing}
                size="24px"
                onChange={e => {
                  publishDps({
                    motor_pairing: !motorPairing,
                  });
                }}
              />
            </Cell>
          ) : null}

          <Cell
            title={Strings.getLang('motor_speed_regulation')}
            value={Strings.getLang(speed)}
            isLink
            onClick={() => {
              setTitle('motor_speed_regulation');
              setList(speedActions);
            }}
          />

          {false ? (
            <Cell
              title={Strings.getLang('control_back')}
              value={Strings.getLang(`c_${controlBack}`)}
              border={false}
              isLink
              onClick={() => {
                setTitle('control_back');
                setList(controlActions);
              }}
            />
          ) : null}

          <Cell title={Strings.getLang('control_back')} border={false}>
            <Switch
              checked={motorReverse}
              size="24px"
              onChange={e => {
                publishDps({
                  motor_reverse: !motorReverse,
                });
              }}
            />
          </Cell>

          <Dialog id="smart-dialog2" />
          <ActionSheet
            show={show}
            title={Strings.getLang(title)}
            actions={list}
            onClose={onClose}
            onSelect={onSelect}
            onCancel={onCancel}
            activeColor="#007AFF"
          />
        </CellGroup>
      </View>
    </View>
  );
}
